package com.sibbay.syncbox.adapter;

import java.io.File;
import java.util.Stack;

import android.util.Log;

import com.sibbay.syncbox.Config;
import com.sibbay.syncbox.syncdb.SyncDatabase;
import com.sibbay.syncbox.syncdb.SyncDatabase.RowIterator;
import com.sibbay.syncbox.syncdb.SyncDatabase.SyncConst;
import com.sibbay.syncbox.utils.FileIterator;

// this process should be started by timer or other way
// scan media and compare with sync database 
// put new files into sync database


public class MediaScannerThread extends Thread {
	private static final String TAG = MediaScannerThread.class.getSimpleName();
	
	final SyncDatabase mSyncDatabase; 
	final Object mLock = new Object();
	private Runnable mOnUpdateRun = null;
	
	public MediaScannerThread(final SyncDatabase syncDatabase) {
		mSyncDatabase = syncDatabase;
	}
	
	public void rescan() {
		mLock.notify();
	}
	
	// call onUpdate if has new files
	public void setOnUpdate(final Runnable run) {
		mOnUpdateRun = run;
	}
	
	@Override
	public void run() {
		while (true) {
			try {
				mLock.wait();
			} catch (InterruptedException e) {
				Log.w(TAG, "is interrupted");
				return;
			}
			
			if (scanDirectoris(mSyncDatabase) && mOnUpdateRun != null)
				mOnUpdateRun.run();
		}
	}

	///
	
	static boolean scanDirectoris(final SyncDatabase db) {
		final RowIterator dirIter = db.getRowIterator(SyncConst.KEY_TYPE_DIR);
		if (!dirIter.moveToFirst()) {
			dirIter.close();
			return false;
		}
		boolean ret = false;
		do {
			final File dir = new File(dirIter.getName());
			if (dir.exists()) {
				if (dir.lastModified() != dirIter.getLastModified()) {
					// directory is changed , scan all subdirectories
					ret = ret || scanFiles(db, dir); 
					db.changeLastModified(dir.getAbsolutePath(), dir.lastModified());
				}
//			} else {
//				// directory doesn't exist, remove all from database 
//				db.deleteName(dirIter.getName());
			}
		} while (dirIter.moveToNext());
		
		dirIter.close();
		return ret;
	}
	
	static boolean scanFiles(final SyncDatabase db, final File dir) {
		final FileIterator fileIter = new FileIterator(dir);
		if (!fileIter.moveToFirst()) {
			return false;
		}
		boolean ret = false;
		do {
			final File f = fileIter.getFile();
			if (!db.hasName(f.getAbsolutePath())) {
				db.insertName(f.getAbsolutePath(), SyncConst.KEY_TYPE_FILE, f.lastModified());
				ret = true;
			}
		} while (fileIter.moveToNext());
		
		return ret;
	}
}
